import sys
import threading
from wsgiref  import simple_server
#from wsgiref.simple_server import make_server, demo_app
#from wsgiref.simple_server import make_server
from selenium import webdriver
#from myapp    import model
from amodel   import Amodel
from flaskr   import app


def before_all(context):
  print("initializing behave tests")
  #return
  #web_app = demo_app
  context.server = context.thread = context.browser = None

  try:
    #context.server = simple_server.WSGIServer(('', 8000))
    #context.server = make_server('' , 8000 , app)
    context.server = simple_server.make_server('' , 8000 , app.test_client())
    #context.server.set_app(app.main(environment='test'))
    #context.server.set_app(app.test_client())
    context.thread = threading.Thread(target = context.server.serve_forever)
    context.thread.start()
    context.browser = webdriver.Firefox()
  except:
    print("behave init failed")
    dump_exception('before_all()')
    after_all(context)


def after_all(context):
  print("cleanup behave tests")
  if context.server  != None: context.server.shutdown()
  if context.thread  != None: context.thread.join()
  if context.browser != None: context.browser.quit()


def before_feature(context , feature):
  try:
    #Amodel.init(environment = 'test')
    context.amodel = Amodel()
  except:
    dump_exception('before_feature()')


def dump_exception(src):
  print( "EXCEPTION in %s: %s %s" % (src , sys.exc_info()[0] , sys.exc_info()[1]))
